package com.tenton.netty.unicast.custom;

import com.tenton.netty.pool.ThreadPool;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioDatagramChannel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

/**
 * @ClassName： UnicastCustomerService
 * @Description： 单播客户端
 * @Author： tangdong
 * @Date： 2024/7/4 09:35
 */
@Component
@Slf4j
public class UnicastCustomerService implements CommandLineRunner {
    @Override
    public void run(String... args) throws Exception {
        ThreadPool.dataDealThreadPool.execute(() -> {
            start();
        });
        log.info("Udp单播接收端启动成功，绑定端口为：{}", 8888);
    }
    private void start() {
        NioEventLoopGroup group = new NioEventLoopGroup();
        Bootstrap bootstrap = new Bootstrap();
        bootstrap.group(group)
                .channel(NioDatagramChannel.class)
                .option(ChannelOption.SO_BROADCAST, true)
                .handler(new ChannelInitializer<NioDatagramChannel>() {
                    @Override
                    protected void initChannel(NioDatagramChannel channel) throws Exception {
                        channel.pipeline().addLast(new UnicastCustomerHandler());
                    }
                });
        try {
            Channel channel = bootstrap.bind(8888).sync().channel();
            channel.closeFuture().sync();
            group.shutdownGracefully();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
